package com.app.controller;

import cn.hutool.json.JSONObject;
import com.app.aop.LoginCheck;
import com.app.aop.BodyParamNotNull;
import com.app.pojo.Status;
import com.app.pojo.UserInfo;
import com.app.service.impl.CaptchaService;
import com.app.service.impl.UserService;
import com.app.utils.R;
import com.app.utils.TokenManager;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;

@RestController()
public class UserController {
    final int maxAge=30*60;
    private final UserService userService;
    private final TokenManager tokenManager;
    private CaptchaService captchaService;

    public UserController(UserService userService, TokenManager tokenManager, CaptchaService captchaService) {
        this.userService = userService;
        this.tokenManager = tokenManager;
        this.captchaService = captchaService;
    }

    /**
     * 用户登录，登录通过则添加记录，返回 cookie
     * @param body  account 用户邮箱或者用户名,password 用户密码
     * @return json数据
     */
    @PostMapping(value = "login")
    @ResponseBody
    @BodyParamNotNull(params = {"account","password"})
    public R loginUser(@RequestBody Map<String,Object> body ){
        System.out.println("登录");
        System.out.println("body = " + body);
        String account=body.get("account").toString();
        String password=body.get("password").toString();
//        MD5 md5=MD5.create();
//        password=md5.digestHex(password);//将密码转为 md5
        if (ObjectUtils.isEmpty(account)||ObjectUtils.isEmpty(password)) return R.error("参数错误");

        String userId;
        if (account.contains("@"))
            userId=userService.loginByEmail(account,password);
        else userId=userService.loginByName(account,password);
        if(!ObjectUtils.isEmpty(userId)){//验证通过，返回token
            String token=tokenManager.addLoginState(userId,password);
            return R.ok().data(new JSONObject().set("token",token).set("userInfo",userService.getUserInfoById(userId)));
        }else return R.error("登录失败");
    }
    /**
     * 用户注册，注册完成返回结果
     * @return json数据：captchaVerify : "OK"或者"FAIL", status 意义根据前者变化
     */
    @PostMapping(value = "register")
    @ResponseBody
    @BodyParamNotNull(params = {"captcha_id","captcha","username","password","email"})
    public R userRegister(@RequestBody Map<String,Object> body){
//        bodypassword=MD5.create().digestHex(password);//将密码转为 md5
        System.out.println("body = " + body);
        String captcha_id=body.get("captcha_id").toString();
        String captcha=body.get("captcha").toString();
        boolean verifyRes = captchaService.verifyCaptcha(captcha_id,captcha);
        if (verifyRes){//验证码验证通过
            String username=body.get("username").toString();
            String password=body.get("password").toString();
            String email=body.get("email").toString();
            if (userService.isUserExist(username,email)) return R.error("用户已存在");
            if (userService.register(username,password,email)) return R.ok().put("captchaVerify","OK");
            else return R.error().put("captchaVerify","OK");
        } else return R.error("验证码错误或失效").put("captchaVerify","FAIL");
    }

    @GetMapping(value = "test")
    public String doTest(HttpServletRequest request,HttpServletResponse response){
        System.out.println("doTest!");
        response.setContentType("application/json;charset=utf-8");
        response.setCharacterEncoding("utf-8");
        JSONObject jsonObject=new JSONObject();
        jsonObject.set("aaa","assasas");
        jsonObject.set("bbb","assasas");
        jsonObject.set("ccc",123);
        jsonObject.set("ddd",true);
        return jsonObject.toString();
    }

    /**
     * 获取用户信息
     * @return json数据
     */
    @LoginCheck
    @GetMapping(value = "getUserInfo")
    public R getUserInfo(String userId){
        //获取用户信息
        if (userId==null) return R.error("参数错误");

        UserInfo userInfo = userService.getUserInfoById(userId);
        if (ObjectUtils.isEmpty(userInfo)) return R.error("没找到用户"+userId);
        return R.ok().data(userInfo);

    }
}
